<?php
/**
 * Created by PhpStorm.
 * User: 陈艺赫
 * Date: 2018/5/12
 * Time: 21:15
 */

namespace app\admin\controller;

use app\user\model\Functions;
use app\user\model\Group;
use app\user\model\User;
use app\user\model\Menu;
use think\Db;

class Auth extends Base
{
    public function allUser()
    {
        return view();
    }

    public function allGroup()
    {
        return view();
    }

    public function allMenu()
    {
        $main_menus = Db::name('menu')
            ->where('pid', null)
            ->whereOr('pid', 0)
            ->order('sort', 'asc')
            ->select();
        $data = [];
        foreach ($main_menus as $main) {
            $main['subject'] = Db::name('menu')
                ->where('pid', $main['id'])
                ->order('sort', 'asc')
                ->select();
            $data[] = $main;
        }
        $this->assign('menus', $data);
        return view();
    }

    /*
     * 系统设置修改页面
     * */
    public function configSet()
    {
        $pwd = config('password');
        $default_pwd = config('default_pwd');
        $district = config('district');
        $this->assign('password', $pwd);
        $this->assign('default_pwd', $default_pwd);
        $this->assign('district', $district);
        return view();
    }

    /*
     * 系统设置修改提交(慎用,慎改)
     * */
    public function editConfigPost()
    {
        if ($this->request->isPost()) {
            $pwd = input('post.password');
            $default_pwd = input('post.default_pwd');

            if ($pwd != config('password')) {
                $user_ids = User::name('user')->column('id');

                $salt = null;
                $salt = is_null($salt) ? random_string(5) : $salt;
                $password = $default_pwd . $salt . $pwd;
                $password = md5(md5($password));

                $user['pwd'] = $password;
                $user['salt'] = $salt;

                Db::name('user')->where('id', 'in', $user_ids)->update($user);
            }


            $this->setConfig(['password'], [$pwd]);
            $this->setConfig(['default_pwd'], [$default_pwd]);
            $district = input('post.district');

            if (!empty($district) && $district == 'on') {
                $this->setConfig(['district'], ['T']);
            } else {
                $this->setConfig(['district'], ['F']);
            }
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    /*
    * 改变用户状态
    */
    public function userStatusChange()
    {
        $id = input('post.id');
        $status = input('post.status');
        if ($status == 1) {
            $msg = '已开启当前账户';
        } else {
            $msg = '已关闭当前用户';
        }
        $user = User::get($id);
        $user->status = $status;
        if ($user->save() !== false) {
            $this->success($msg);
        } else {
            $this->error('未能执行操作,请联系管理员');
        }
    }

    /*
     * 被打开的用户所有信息
     * */
    public function showUserInfo()
    {
        $id = input('get.id');
        $user = new User();
        $user_info = $user->with('parent')->find($id)->toArray();
        $all_user = $user
            ->field('id, nickname')
            ->where('status', '1')
            ->select();
        $group = Db::name('group')
            ->field('id,name')
            ->where('status', '1')
            ->select();
//        dump($user_info);
        $this->assign('users', $all_user);
        $this->assign('info', $user_info);
        $this->assign('groups', $group);
        return view();
    }

    /*
     * 修改用户信息提交
     * */
    public function editUserPost()
    {
        $data = input('post.');
        if (!empty($data)) {
            $db_user = new User();
            $user = $db_user->find($data['id']);
            $user->nickname = $data['nickname'];
            if (!empty($data['group'])) {
                $user->group_ids = implode(',', $data['group']);
            }
            $user->save();
            if (!empty($data['pid'])) {
                Db::name('user_pid')->where('user_id', $data['id'])->delete(true);
                $insert_data = [];
                foreach ($data['pid'] as $v) {
                    $insert_data[] = ['user_id' => $data['id'], 'user_pid' => $v];
                }
                Db::name('user_pid')->insertAll($insert_data);
            }
        }
        $this->success('修改成功!');
    }

    /*
     * 新增用户界面
     * */
    public function showAddUser()
    {
        $user = new User();
        $all_user = $user
            ->field('id, nickname')
            ->where('status', '1')
            ->select();
        $group = Db::name('group')
            ->field('id,name')
            ->where('status', '1')
            ->select();
        $this->assign('users', $all_user);
        $this->assign('groups', $group);
        return view();
    }

    /*
     * 新增用户
     * */
    public function addUserPost()
    {
        $data = input('post.');
        if (!empty($data)) {
            if (!empty($data['group'])) {
                $data['group_ids'] = implode(',', $data['group']);
            }
            $pas = User::makePasswordAndSalt(config('default_pwd'));
            $data['salt'] = $pas['salt'];
            $data['pwd'] = $pas['password'];
            $result = Db::name('user')->insert($data);
            if ($result > 0) {
                $id = Db::getLastInsID();
                if (!empty($data['pid'])) {
                    $insert_data = [];
                    foreach ($data['pid'] as $v) {
                        $insert_data[] = ['user_id' => $id, 'user_pid' => $v];
                    }
                    Db::name('user_pid')->insertAll($insert_data);
                }
            } else {
                $this->error('用户名成功!');
            }

        }
        $this->success('新增用户成功!');
    }

    /*
     * 修改密码
     * */
    public function showChangePwd()
    {
        $id = input('get.id');
        $user = new User();
        $user_info = $user->find($id);
        $this->assign('info', $user_info);
        return view();
    }

    /*
     * 修改密码提交
     * */
    public function editPwdPost()
    {
        $id = input('post.id');
        $old_pwd = input('post.old_pwd');
        $new_pwd = input('post.new_pwd');
        $user = Db::name('user')->find($id);
        // 校验密码
        $password = $old_pwd . $user['salt'] . config('password');
        $password = md5(md5($password));
        $hash = $user['pwd'];
        if ($password !== $hash) {
            $error = '密码错误，请重新输入！';
            $this->error($error);
        } else {
            $temp = User::makePasswordAndSalt($new_pwd);
            $user['pwd'] = $temp['password'];
            $user['salt'] = $temp['salt'];
            Db::name('user')->update($user);
            $this->success('密码修改成功');
        }
    }

    /*
     * 改变menu状态
     * */
    public function menuStatusChange()
    {
        if ($this->request->isPost()) {
            $id = input('post.id');
            $menu = Db::name('menu')->find($id);
            $menu['status'] = ($menu['status'] == 1) ? 0 : 1;
            Db::name('menu')->update($menu);
            $this->success('修改成功');
        } else {
            $this->error('数据传输错误');
        }
    }

    /*
     * 新增menu页面
     * */
    public function showAddMenu()
    {
        $data = Db::name('menu')
            ->where('status', '1')
            ->where('pid', null)
            ->whereOr('pid', 0)
            ->select();
        $this->assign('menus', $data);
        return view();
    }

    /*
     * 新增menu提交
     * */
    public function addMenuPost()
    {
        if ($this->request->isPost()) {
            $data = input('post.');
            $result = Db::name('menu')->insert($data);
            if ($result !== 0) {
                $this->success('新增成功');
            } else {
                $this->error('新增失败');
            }
        } else {
            $this->error('数据传输错误');
        }
    }

    /*
     * 修改menu页面
     * */
    public function showEditMenu()
    {
        if ($this->request->isGet()) {
            $id = input('get.id');
            $data = Db::name('menu')
                ->where('status', '1')
                ->where('pid', null)
                ->whereOr('pid', 0)
                ->select();
            $menu = Db::name('menu')->find($id);
            $this->assign('menu', $menu);
            $this->assign('menus', $data);
            return view();
        }
    }

    /*
     * 修改menu提交
     * */
    public function editMenuPost()
    {
        if ($this->request->isPost()) {
            $data = input('post.');
            $result = Db::name('menu')->update($data);
            if ($result > 0) {
                $this->success('修改成功');
            } else {
                $this->success('修改失败');
            }
        } else {
            $this->error('数据传输错误');
        }
    }

    /**
     * 修改config的函数
     * @param $arr1 配置前缀
     * @param $arr2 数据变量
     * @return bool 返回状态
     */
    private function setConfig($pat, $rep)
    {
        /**
         * 原理就是 打开config配置文件 然后使用正则查找替换 然后在保存文件.
         * 传递的参数为2个数组 前面的为配置 后面的为数值.  正则的匹配为单引号  如果你的是分号 请自行修改为分号
         * $pat[0] = 参数前缀;  例:   default_return_type
         * $rep[0] = 要替换的内容;    例:  json
         */
        if (is_array($pat) and is_array($rep)) {
            for ($i = 0; $i < count($pat); $i++) {
                $pats[$i] = '/\'' . $pat[$i] . '\'(.*?),/';
                $reps[$i] = "'" . $pat[$i] . "'" . "=>" . "'" . $rep[$i] . "',";
            }
            $fileurl = APP_PATH . "config.php";
            $string = file_get_contents($fileurl); //加载配置文件
            $string = preg_replace($pats, $reps, $string); // 正则查找然后替换
            file_put_contents($fileurl, $string); // 写入配置文件
            return true;
        } else {
            return flase;
        }
    }

    /*
     * 用户组edit页面显示
     * */
    public function showEditGroup()
    {
        if ($this->request->isGet()) {
            $id = input('get.id');
            $data = Db::name('group')->find($id);
            $menus = Group::getGroupMenuIds($id);
            $this->assign('group', $data);
            $this->assign('menus', $menus);
        }
        $data_all_menus = Menu::getUserMenus(session('id'));
        $this->assign('all_menus', $data_all_menus);
        return view();
    }

    /*
     * 用户组edit提交
     * */
    public function editGroupPost()
    {
        if ($this->request->isPost()) {
            $data = input('post.');
            $data['menu_ids'] = implode(',', $data['menu_ids']);
            unset($data['menu_id']);
            Db::name('group')->update($data);
            $this->success('修改成功');
        } else {
            $this->error('数据传输错误');
        }
    }

    /*
     * 用户组新增页面
     * */
    public function showAddGroup()
    {
        $data_all_menus = Menu::getUserMenus(session('id'));
        $this->assign('all_menus', $data_all_menus);
        return view();
    }

    /*
     * 用户组新增提交
     * */
    public function addGroupPost()
    {
        if ($this->request->isPost()) {
            $data = input('post.');
            unset($data['menu_id']);
            $data['menu_ids'] = implode(',', $data['menu_ids']);
            $result = Db::name('group')->insert($data);
            if ($result !== 0) {
                $this->success('新增成功');
            } else {
                $this->error('新增失败');
            }
        }
    }

    /*
     * 用户组状态变更
     * */
    public function groupStatusChange(){
        $id = input('post.id');
        $status = input('post.status');
        if ($status == 1) {
            $msg = '已开启当前用户组';
        } else {
            $msg = '已关闭当前用户组';
        }
        $group = Group::get($id);
        $group->status = $status;
        if ($group->save() !== false) {
            $this->success($msg);
        } else {
            $this->error('未能执行操作,请联系管理员');
        }
    }

    /*
     * 权限变更页面
     * */
    public function showEditGroupAuth(){
        if ($this->request->isGet()){
            $group_id = input('get.id');
            $funcs = Group::get($group_id)->func_ids;
            $all_funcs = Functions::all();
            $this->assign('all_funcs',$all_funcs);
            $this->assign('funcs',$funcs);
        }

        return view();
    }

    /*
     * 权限变更页面
     * */
    public function editGroupAuthPost(){
        if ($this->request->isPost()){
            $data = input('post.');
            Db::name('group')->update($data);
            $this->success('修改成功');
        }else{
            $this->error('数据传输错误');
        }

    }
}

